//
//  UDRefreshControl.swift
//  AutoPrint
//
//  Created by 胡玉葱 on 16/9/28.
//  Copyright © 2016年 fatcat. All rights reserved.
//  下拉刷新控制器

import UIKit

enum UDRefreshControllerState {
    case normal
    case ready
    case refreshing
}

class UDRefreshControl: UIView {
    
    var titleLabel: UILabel!
    fileprivate var normalText = "下拉刷新"
    fileprivate var readyText = "松开刷新"
    fileprivate var refreshingText = "正在刷新"
    var normalTitle: String{
        get{
            return normalText
        }
        set(val){
            normalText = val
            if state == .normal{
                titleLabel.text = val
            }
        }
    }
    var readyTitle: String{
        get{
            return readyText
        }
        set(val){
            readyText = val
            if state == .ready{
                titleLabel.text = val
            }
        }
    }
    var refreshingTitle: String{
        get{
            return refreshingText
        }
        set(val){
            refreshingText = val
            if state == .refreshing{
                titleLabel.text = val
            }
        }
    }
    var state: UDRefreshControllerState = .normal
    
    var spinn: UIActivityIndicatorView!
    
    override init(frame: CGRect){
        super.init(frame: frame)
        titleLabel = UILabel(frame: CGRect(x: 0, y: frame.height-16-16, width: 64, height: 16))
        titleLabel.center.x = center.x
        titleLabel.textAlignment = .center
        titleLabel.textColor = UIColor.lightGray
        titleLabel.font = UIFont.systemFont(ofSize: 12)
        titleLabel.text = normalText
        addSubview(titleLabel)
        
        spinn = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        spinn.hidesWhenStopped = true
        spinn.center = CGPoint(x: titleLabel.center.x - 64, y: titleLabel.center.y)
        addSubview(spinn)
    }
    
    func readyToRefresh(){
        state = .ready
        titleLabel.text = readyText
    }
    
    func beginRefresh(){
        state = .refreshing
        titleLabel.text = refreshingText
        spinn.startAnimating()
    }
    
    func endRefresh(){
        state = .normal
        titleLabel.text = normalText
        spinn.stopAnimating()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */

}
